<template>
    <div class="schedule-page">
        <el-breadcrumb separator="/" class="header">
            <el-breadcrumb-item :to="{ path: '/jiaoxue/class' }">班级管理</el-breadcrumb-item>
            <el-breadcrumb-item>课程表</el-breadcrumb-item>
        </el-breadcrumb>

        <div class="schedule-container">
            <div class="class-info">
                <h2 class="class-name">{{ classInfo?.className || '未选择班级' }}</h2>

                <div class="operation-area">
                    <el-button type="primary" @click="handleNew" class="new-btn">
                        <el-icon>
                            <Plus />
                        </el-icon>
                        新建
                    </el-button>
                </div>
            </div>

            <div class="schedule-content">
                <el-calendar v-model="value">
                    <template #date-cell="{ data }">
                        <div class="calendar-day-content" style="cursor: pointer;" @click="handleDateClick(data.day)">
                            <span class="day-number">{{ data.day.split('-').slice(2).join('-') }}</span>
                            <div class="course-notes">
                                <template v-for="(course, idx) in scheduleMap[data.day]" :key="course.id">
                                    <div class="note-item" :title="course.notes" @click="handleNoteClick(course)"
                                        :class="{ 'active': currentCourse?.id === course.id }">
                                        <span class="red-dot"></span>
                                        <span class="note-text">{{ course.notes }}</span>
                                        <el-icon class="delete-icon" @click.stop="handleDeleteCourse(course.id, $event)"
                                            title="删除课程">
                                            <Close />
                                        </el-icon>
                                    </div>
                                </template>
                            </div>
                        </div>
                    </template>
                </el-calendar>
            </div>
        </div>

        <el-drawer title="新建课程" v-model="drawerVisible" size="50%" :before-close="handleClose">
            <el-form :model="form" label-width="120px" :rules="rules" ref="formRef" label-position="top">
                <el-form-item label="上课日期" prop="courseDate">
                    <el-date-picker v-model="form.courseDate" type="date" placeholder="选择日期" style="width: 100%"
                        value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="课程内容" prop="notes">
                    <el-input v-model="form.notes" type="textarea" placeholder="输入课程内容" />
                </el-form-item>
                <el-form-item label="开始/结束时间" prop="startTime">
                    <el-time-select v-model="form.startTime" style="width: 240px;" :max-time="form.endTime"
                        placeholder="选择开始时间" start="00:00" step="00:15" end="24:00" format="HH:mm" />
                    <span style="margin: 0 15px">—</span>
                    <el-time-select v-model="form.endTime" style="width: 240px" :min-time="form.startTime"
                        placeholder="选择结束时间" start="00:00" step="00:15" end="24:00" format="HH:mm" />
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleCancel">取消</el-button>
                    <el-button type="primary" @click="handleAdd">确认</el-button>
                </div>
            </template>
        </el-drawer>

        <el-drawer title="编辑课程" v-model="editDrawerVisible" size="50%" :before-close="handleEditClose">
            <el-form :model="editForm" label-width="120px" :rules="rules" ref="editFormRef" label-position="top">
                <el-form-item label="上课日期" prop="courseDate">
                    <el-date-picker v-model="editForm.courseDate" type="date" placeholder="选择日期" style="width: 100%"
                        value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="课程内容" prop="notes">
                    <el-input v-model="editForm.notes" type="textarea" placeholder="输入课程内容" />
                </el-form-item>
                <el-form-item label="开始/结束时间" prop="startTime">
                    <el-time-select v-model="editForm.startTime" style="width: 240px;" :max-time="editForm.endTime"
                        placeholder="选择开始时间" start="00:00" step="00:15" end="24:00" format="HH:mm" />
                    <span style="margin: 0 15px">—</span>
                    <el-time-select v-model="editForm.endTime" style="width: 240px" :min-time="editForm.startTime"
                        placeholder="选择结束时间" start="00:00" step="00:15" end="24:00" format="HH:mm" />
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="handleEditCancel">取消</el-button>
                    <el-button type="primary" @click="handleUpdate">确认修改</el-button>
                </div>
            </template>
        </el-drawer>
    </div>
</template>

<script setup>
import { ref, onMounted, reactive, watch, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRoute } from 'vue-router'
import { Plus, Close } from '@element-plus/icons-vue'
import { addSchedule, getScheduleList, deleteSchedule, updateSchedule } from '../../../api/schedule/schedule.js'
import { useWebSocketStore } from '../../../stores/websocket'

// 路由与基础状态
const route = useRoute()
const value = ref(new Date())
const classInfo = ref(null)
const drawerVisible = ref(false)
const formRef = ref(null)
const editDrawerVisible = ref(false)
const editFormRef = ref(null)
const currentCourse = ref(null)
const scheduleList = ref([])
const selectedDate = ref(new Date().toISOString().split('T')[0])

// 表单数据
const form = reactive({
    courseDate: new Date().toISOString().split('T')[0],
    notes: '',
    startTime: '20:00',
    endTime: '22:00'
})

const editForm = reactive({
    courseDate: new Date().toISOString().split('T')[0],
    notes: '',
    startTime: '20:00',
    endTime: '22:00'
})

// 表单校验规则
const rules = reactive({
    courseDate: [
        { required: true, message: '请选择上课日期', trigger: 'change' }
    ],
    notes: [
        { required: true, message: '请输入课程内容', trigger: 'blur' },
        { min: 2, max: 200, message: '课程内容长度在 2 到 200 个字符', trigger: 'blur' }
    ],
    startTime: [
        { required: true, message: '请选择开始时间', trigger: 'change' }
    ],
    endTime: [
        { required: true, message: '请选择结束时间', trigger: 'change' },
        {
            validator: (rule, value, callback) => {
                const formData = editDrawerVisible.value ? editForm : form
                if (formData.startTime && value && formData.startTime >= value) {
                    callback(new Error('结束时间必须晚于开始时间'));
                } else {
                    callback();
                }
            },
            trigger: 'change'
        }
    ]
})

// 课程数据映射（按日期分组）
const scheduleMap = computed(() => {
    const map = {}
    scheduleList.value.forEach(course => {
        if (!map[course.courseDate]) {
            map[course.courseDate] = []
        }
        map[course.courseDate].push(course)
    })
    return map
})

/**
 * 获取课程列表
 */
const fetchScheduleList = async () => {
    if (!classInfo.value?.classId) return
    try {
        const res = await getScheduleList({ classId: classInfo.value.classId })
        if (res.code === 200) {
            scheduleList.value = res.rows
            if (currentCourse.value) {
                const exists = scheduleList.value.some(c => c.id === currentCourse.value.id)
                if (!exists) {
                    currentCourse.value = null
                }
            }
        } else {
            ElMessage.warning('获取课程列表失败：' + (res.msg || '未知错误'))
        }
    } catch (err) {
        console.error('获取课程列表失败：', err)
        ElMessage.error('获取课程列表失败')
    }
}

/**
 * 日期点击事件
 */
const handleDateClick = (date) => {
    if (!date) return
    selectedDate.value = date
    if (currentCourse.value && currentCourse.value.courseDate !== date) {
        currentCourse.value = null
    }
}

/**
 * 课程点击事件（编辑）
 */
const handleNoteClick = (course) => {
    if (!classInfo.value) {
        ElMessage.warning('请先从班级管理页面进入课程表')
        return
    }

    if (!course || !course.id) {
        ElMessage.warning('课程数据无效')
        return
    }

    currentCourse.value = course
    selectedDate.value = course.courseDate

    editForm.courseDate = course.courseDate
    editForm.notes = course.notes || ''

    // 处理时间格式
    const startParts = course.startTime ? course.startTime.split(' ') : ['', '']
    const endParts = course.endTime ? course.endTime.split(' ') : ['', '']

    editForm.startTime = startParts[1] || '20:00'
    editForm.endTime = endParts[1] || '22:00'

    editDrawerVisible.value = true
}

/**
 * 删除课程
 */
const handleDeleteCourse = async (courseId, e) => {
    e.stopPropagation()
    if (!courseId) return

    try {
        await ElMessageBox.confirm(
            '确定要删除该课程吗？删除后不可恢复',
            '删除确认',
            {
                distinguishCancelAndClose: true,
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )

        await deleteSchedule([courseId])
        ElMessage.success('课程删除成功')
        if (currentCourse.value?.id === courseId) {
            currentCourse.value = null
        }
        fetchScheduleList()
    } catch (error) {
        if (error === 'cancel') {
            ElMessage({ type: 'info', message: '已取消删除' });
        } else if (error === 'close') {
            ElMessage({ type: 'info', message: '已关闭删除确认' });
        } else {
            console.error('删除课程失败：', error);
            ElMessage.error(error.message || '删除课程失败');
        }
    }
}

/**
 * 更新课程
 */
const handleUpdate = async () => {
    if (!editFormRef.value) return
    await editFormRef.value.validate()

    if (!classInfo.value) {
        ElMessage.warning('请先从班级管理页面进入课程表')
        return
    }

    if (!currentCourse.value) {
        ElMessage.warning('未选中任何课程，请刷新页面重试')
        return
    }

    try {
        const startDateTime = `${editForm.courseDate} ${editForm.startTime}`;
        const endDateTime = `${editForm.courseDate} ${editForm.endTime}`;

        const requestData = {
            id: currentCourse.value.id,
            classId: classInfo.value.classId,
            teacherId: classInfo.value.teacherId,
            notes: editForm.notes,
            courseDate: editForm.courseDate,
            startTime: startDateTime,
            endTime: endDateTime
        }

        const res = await updateSchedule(requestData)
        if (res.code === 200) {
            ElMessage.success('课程修改成功')
            currentCourse.value = {
                ...currentCourse.value,
                ...requestData,
                startTime: startDateTime,
                endTime: endDateTime
            }
            editDrawerVisible.value = false
            fetchScheduleList()
        }
    } catch (error) {
        console.error('修改课程失败：', error)
        ElMessage.error(error.message || '修改课程失败')
    }
}

/**
 * 编辑抽屉关闭/取消
 */
const handleEditClose = (done) => done()
const handleEditCancel = () => { editDrawerVisible.value = false }

/**
 * 新建课程
 */
const handleNew = () => {
    if (!classInfo.value) {
        ElMessage.warning('请先从班级管理页面进入课程表')
        return
    }
    const selectedDateVal = selectedDate.value
    const hasCourse = scheduleMap.value[selectedDateVal] && scheduleMap.value[selectedDateVal].length > 0

    if (hasCourse) {
        ElMessage.warning('该日期已有课程安排')
        return
    }

    formRef.value?.resetFields()
    form.courseDate = selectedDateVal
    drawerVisible.value = true
}

/**
 * 新建抽屉关闭/取消
 */
const handleClose = (done) => done()
const handleCancel = () => { drawerVisible.value = false }

/**
 * 提交新增课程（仅此处调用自定义通知）
 */
const handleAdd = async () => {
    if (!formRef.value) return
    await formRef.value.validate()

    if (!classInfo.value) {
        ElMessage.warning('请先从班级管理页面进入课程表')
        return
    }

    try {
        const startDateTime = `${form.courseDate} ${form.startTime}`;
        const endDateTime = `${form.courseDate} ${form.endTime}`;

        const requestData = {
            classId: classInfo.value.classId,
            teacherId: classInfo.value.teacherId,
            notes: form.notes,
            courseDate: form.courseDate,
            startTime: startDateTime,
            endTime: endDateTime
        }

        const res = await addSchedule(requestData)
        drawerVisible.value = false
        fetchScheduleList()
    } catch (error) {
        console.error('新增课程失败：', error)
        ElMessage.error(error.message || '新增课程失败')
    }
}

// 生命周期
onMounted(async () => {
    // 解析班级信息
    try {
        const classDataStr = route.query.classData
        if (classDataStr) {
            const classData = JSON.parse(decodeURIComponent(classDataStr))
            classInfo.value = classData
        } else {
            ElMessage.warning('未获取到班级信息')
        }
    } catch (error) {
        console.error('解析班级信息失败：', error)
        ElMessage.error('解析班级信息失败')
    }

    // 加载课程列表
    fetchScheduleList()

    // 初始化WebSocket路由信息
    const wsStore = useWebSocketStore()
    if (!wsStore.currentRoute) {
        wsStore.currentRoute = route.path || ''
    }
})

// 监听表单深层变化
watch(form, () => { }, { deep: true })
</script>

<style scoped>
.schedule-page {
    width: 100%;
    height: 100%;
    padding: 20px;
    box-sizing: border-box;
    background-color: #fff;
}

.header {
    padding: 15px 0;
    font-size: 20px;
    color: #333;
}

.schedule-container {
    box-sizing: border-box;
}

.class-info {
    display: flex;
    margin-bottom: 10px;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
}

.class-name {
    margin: 0 0 12px 0;
    font-size: 22px;
    font-weight: 600;
    color: #2d3748;
}

.schedule-content {
    display: flex;
    gap: 20px;
}

:deep(.el-calendar) {
    width: 100%;
    border: 1px solid #ebeef5;
    border-radius: 4px;
}

:deep(.el-calendar__header) {
    margin-bottom: 15px;
    padding: 10px 15px;
    background-color: #f5f7fa;
    border-bottom: 1px solid #ebeef5;
}

:deep(.el-calendar-day) {
    transition: all 0.2s ease;
    height: 80px;
    padding: 5px;
    display: flex;
    flex-direction: column;
}

:deep(.el-calendar-day:hover:not(.is-disabled)) {
    background-color: #edf2ff;
}

:deep(.el-calendar-day.is-today) {
    color: #165dff;
    font-weight: 500;
}

.calendar-day-content {
    display: flex;
    flex-direction: column;
    height: 100%;
    width: 100%;
}

.day-number {
    font-size: 14px;
    margin-bottom: 4px;
}

.course-notes {
    flex: 1;
    overflow: hidden;
    max-height: 75px;
}

.note-item {
    position: relative;
    font-size: 12px;
    color: #165dff;
    margin: 2px 0;
    padding: 2px 8px;
    display: -webkit-box !important;
    -webkit-line-clamp: 2 !important;
    -webkit-box-orient: vertical !important;
    overflow: hidden !important;
    text-overflow: ellipsis;
    line-height: 1.5;
    max-height: 36px;
    display: flex;
    align-items: flex-start;
    justify-content: space-between;
    cursor: pointer;
    transition: all 0.2s ease;
}

.note-item:hover {
    background-color: rgba(22, 93, 255, 0.1);
    border-radius: 2px;
    transform: translateX(2px);
}

.note-item.active {
    background-color: rgba(22, 93, 255, 0.2);
    border-radius: 2px;
}

.red-dot {
    display: inline-block;
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #165dff;
    margin-right: 4px;
    vertical-align: middle;
}

.note-text {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    line-height: inherit;
}

.delete-icon {
    width: 10px;
    height: 10px;
    position: absolute;
    right: 0;
    top: 50%;
    transform: translate(-50%, -50%);
    color: white;
    background-color: #ff4d4f;
    border-radius: 50%;
    padding: 2px;
    margin-left: 6px;
    cursor: pointer;
    transition: all 0.2s ease;
    opacity: 0;
    width: 0;
    overflow: hidden;
    display: inline-flex;
    align-items: center;
    justify-content: center;
}

.note-item:hover .delete-icon {
    opacity: 1;
    width: 10px;
}

.delete-icon:hover {
    background-color: #f5222d;
}

.operation-area {
    margin-bottom: 10px;
    text-align: right;
}

.new-btn {
    padding: 8px 16px;
}

:deep(.el-drawer__body) {
    padding: 20px;
}

:deep(.el-form-item) {
    margin-bottom: 15px;
}

:deep(.el-drawer__footer) {
    padding: 20px;
    border-top: 1px solid rgba(0, 0, 0, 0.09);
}
</style>